//
//  BIDEditCalendarViewController.m
//  TestCalendar
//
//  Created by mal on 14-1-12.
//  Copyright (c) 2014年 mal. All rights reserved.
//

#import "BIDEditCalendarViewController.h"
#import "BIDRecurrenceListViewController.h"

@interface BIDEditCalendarViewController ()<BIDRecurrenceListViewControllerDelegate>

@end

@implementation BIDEditCalendarViewController
@synthesize myDatePicker;
@synthesize myToolBar;
@synthesize reminderContentTextView;
@synthesize reminderTimeTF;
@synthesize reminderRecurrenceTF;
@synthesize delBtn;
@synthesize reminderDate;
@synthesize bEdit;
@synthesize kitController;
@synthesize reminder;
@synthesize recurrenceMode;
@synthesize bDateViewShow;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"提醒设置";
    // Do any additional setup after loading the view from its nib.
    bDateViewShow = NO;
    recurrenceMode = -1;
    if(!bEdit)
    {
        delBtn.hidden = YES;
    }
    else
    {
        delBtn.hidden = NO;
    }
    //
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGRect ownFrame = self.view.frame;
    //
    myDatePicker = [[UIDatePicker alloc] init];
    CGRect datePickerFrame = myDatePicker.frame;
    datePickerFrame = CGRectMake(0, screenSize.height+216, self.view.frame.size.width, 216);
    myDatePicker.frame = datePickerFrame;
    
    //textview
    reminderContentTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    reminderContentTextView.layer.borderWidth = 1;
    reminderContentTextView.layer.cornerRadius = 5;
    reminderContentTextView.inputAccessoryView = self.toolBar;
    
    //UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture1:)];
    //[reminderTimeTF addGestureRecognizer:tap1];

    //UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture2:)];
    //[reminderRecurrenceTF addGestureRecognizer:tap2];
    
    reminderTimeTF.delegate = self;
    reminderRecurrenceTF.delegate = self;
    
    //设置toolbar
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelBtnHandler)];
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleBordered target:self action:@selector(confirmBtnHandler)];

    myToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, screenSize.height-216-30, ownFrame.size.width, 30)];
    NSArray *arr = [[NSArray alloc] initWithObjects:item1, item2, item3, nil];
    myToolBar.items = arr;
    myToolBar.barStyle = UIBarStyleBlackTranslucent;
    //
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleBordered target:self action:@selector(rightBtnHandler)];
    //
    
    if(reminder!=nil)
    {
        //设置提醒标题
        reminderContentTextView.text = reminder.title;
        //提醒的日期
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDate *date = [calendar dateFromComponents:reminder.dueDateComponents];
        [myDatePicker setDate:date];
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"yyyy'年'M'月'd'日' EEEE H:mm"];
        reminderTimeTF.text = [df stringFromDate:myDatePicker.date];
        //提醒的模式
        BOOL bHaveRecurrenceRule = reminder.hasRecurrenceRules;
        
        if(!bHaveRecurrenceRule)
        {
            recurrenceMode = -1;
            reminderRecurrenceTF.text = @"永不";
        }
        else
        {
            NSArray *recurrenceArr = reminder.recurrenceRules;
            EKRecurrenceRule *rule = (EKRecurrenceRule*)[recurrenceArr objectAtIndex:0];
            recurrenceMode = rule.frequency;
            switch(recurrenceMode)
            {
                case 0:
                {
                    reminderRecurrenceTF.text = @"每天";
                }
                    break;
                case 1:
                {
                    reminderRecurrenceTF.text = @"每周";
                }
                    break;
                case 2:
                {
                    reminderRecurrenceTF.text = @"每月";
                }
                    break;
                case 3:
                {
                    reminderRecurrenceTF.text = @"每年";
                }
                    break;
            }
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    myDatePicker = nil;
    myToolBar = nil;
    reminderRecurrenceTF = nil;
    reminderContentTextView = nil;
    reminderTimeTF = nil;
    delBtn = nil;
    reminderDate = nil;
    kitController = nil;
}

- (void)backBtnHandler
{
    if(bDateViewShow)
    {
        bDateViewShow = NO;
        [myToolBar removeFromSuperview];
        [myDatePicker removeFromSuperview];
    }
    //[self.navigationController popViewControllerAnimated:YES];
}

//提醒时间
- (void)tapGesture1:(UIGestureRecognizer *)recognizer
{
    [reminderTimeTF resignFirstResponder];
    [self showDatePicker];
}
//提醒重复
- (void)tapGesture2:(UIGestureRecognizer *)recognizer
{
    BIDRecurrenceListViewController *listViewController = [[BIDRecurrenceListViewController alloc] init];
    listViewController.delegate = self;
    listViewController.modeIndex = recurrenceMode+1;
    [self.navigationController pushViewController:listViewController animated:YES];
}
//删除
- (IBAction)delBtnHandler:(id)sender
{
    BOOL bSuccess = YES;
    bSuccess = [kitController removeReminder:reminder];
    if(bSuccess)
    {
        [BIDGlobalMethods showAlertView:@"删除成功" buttonTitle:@"关闭" delegate:self tag:0];
    }
    else
    {
        [BIDGlobalMethods showAlertView:@"删除失败" buttonTitle:@"关闭" delegate:nil tag:0];
    }
}
//确定
- (void)confirmBtnHandler
{
    self.reminderDate = myDatePicker.date;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy'年'M'月'd'日' EEEE H:mm"];
    reminderTimeTF.text = [df stringFromDate:myDatePicker.date];
    [self dismissDatePicker];
}
//取消日期控件显示
- (void)cancelBtnHandler
{
    [self dismissDatePicker];
}
//完成
- (void)rightBtnHandler
{
    if(reminderContentTextView.text.length==0)
    {
        [BIDGlobalMethods showAlertView:@"请先填写提醒内容" buttonTitle:@"关闭" delegate:nil tag:0];
        return;
    }
    if(reminderTimeTF.text.length==0)
    {
        [BIDGlobalMethods showAlertView:@"请选择提醒时间" buttonTitle:@"关闭" delegate:nil tag:0];
        return;
    }
    
    BOOL bSuccess;
    if(!bEdit)
    {
        //新建提醒
        bSuccess = [kitController addReminderWithTitle:reminderContentTextView.text dueTime:reminderDate mode:recurrenceMode];
    }
    else
    {
        //修改提醒
        reminder.title = reminderContentTextView.text;
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSUInteger unitFlags = NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit;
        NSDateComponents *dueDateComponents = [calendar components:unitFlags fromDate:myDatePicker.date];
        reminder.dueDateComponents = dueDateComponents;
        if(recurrenceMode==-1)
        {
            reminder.recurrenceRules = nil;
        }
        else
        {
            EKRecurrenceRule *rule = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency:recurrenceMode interval:1 end:nil];
            reminder.recurrenceRules = @[rule];
        }
        
        bSuccess = [kitController saveRminder:reminder];
    }
    NSString *msg;
    if(bSuccess)
    {
        msg = @"操作成功";
        [BIDGlobalMethods showAlertView:msg buttonTitle:@"关闭" delegate:self tag:0];
    }
    else
    {
        msg = @"操作失败";
        [BIDGlobalMethods showAlertView:msg buttonTitle:@"关闭" delegate:nil tag:0];
    }
    
}
//取消提醒的创建或修改
- (void)leftBtnHandler
{
    if(bDateViewShow) [self dismissDatePicker];
    [self.navigationController popViewControllerAnimated:YES];
}

//
- (void)showDatePicker
{
    if(bDateViewShow) return;
    bDateViewShow = YES;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:myDatePicker];
    [UIView animateWithDuration:0.5f animations:^{
        CGRect frame = myDatePicker.frame;
        frame.origin.y = screenSize.height - myDatePicker.frame.size.height;
        myDatePicker.frame = frame;
    } completion:^(BOOL finished){
        if(finished)
        {
            [keyWindow addSubview:myToolBar];
        }
    }];
}

//
- (void)dismissDatePicker
{
    bDateViewShow = NO;
    [myToolBar removeFromSuperview];
    [UIView animateWithDuration:0.5f animations:^{
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        CGRect frame = myDatePicker.frame;
        frame.origin.y = screenSize.height+216;
        myDatePicker.frame = frame;
    } completion:^(BOOL finished){
        if(finished)
        {
            [myDatePicker removeFromSuperview];
        }
    }];
}

#pragma mark UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    switch (textField.tag)
    {
        case 0:
        {
            //提醒时间
            [reminderTimeTF resignFirstResponder];
            [self showDatePicker];
        }
            break;
        case 1:
        {
            //提醒的重复模式
            [reminderRecurrenceTF resignFirstResponder];
            BIDRecurrenceListViewController *listViewController = [[BIDRecurrenceListViewController alloc] init];
            listViewController.delegate = self;
            listViewController.modeIndex = recurrenceMode+1;
            [self.navigationController pushViewController:listViewController animated:YES];
        }
            break;
    }
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark BIDRecurrenceListViewControllerDelegate
//str1为传过来的重复模式的名字，str2用不到
- (void)getModeType:(NSString *)modeType atIndex:(NSInteger)index
{
    if([modeType isEqualToString:@"无"]) modeType = @"永不";
    reminderRecurrenceTF.text = modeType;
    if(index==0)
    {
        recurrenceMode = -1;
    }
    else
    {
        recurrenceMode = index-1;
    }
}

@end
